<?php

namespace App\Http\Controllers\Api;

use App\Events\addLog;
use App\Http\Controllers;
use App\Http\Requests\UserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controllers\Controller
{


    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $query = User::query();
        $models = $query->when($keyword, function ($queryString) use ($keyword) {
            return $queryString->where('name', 'like', '%' . $keyword . '%');
        })->orderByDesc('id')->paginate();
        return UserResource::collection($models);
    }

    public function store(UserRequest $request)
    {
        $data = $request->all();
        $model = new User();
        $model->fill($data);
        $model->save();
        event(new addLog(Auth::user(),'添加'.$model->name));
        return new UserResource($model);
    }


    public function show($id)
    {
        $model = $this->findModel($id);
        return new UserResource($model);
    }


    public function update(UserRequest $request, $id)
    {
        $data = $request->all();
        $model = $this->findModel($id);
        $model->fill($data);
        $model->save();
        event(new addLog(Auth::user(),'修改'.$model->name.'信息'));
        return new UserResource($model);
    }


    public function destroy($id)
    {
        $model = $this->findModel($id);
        $model->delete();
        event(new addLog(Auth::user(),'删除了'.$model->name));
        return response()->json(['state'=>'success']);

    }


    public function findModel($id){
        $model = User::query()->where('id',$id)->first();
        return $model;
    }

}
